<?php
/**
 * 文件上传
 * Author: huangzhen
 * Date: 2021/01/18
 */
namespace app\cardeadmin\controller;
use app\common\controller\AdminController;
use think\facade\Request;

class Uploads extends AdminController
{

    //上传验证规则
    protected $uploadValidate = [
        'image' => 'filesize:102400|fileExt:jpg,png,gif,jpeg,rar,zip,avi,mp4,rmvb,3gp,flv,mp3,txt,doc,xls,ppt,pdf,xls,docx,xlsx,doc'
    ];
    protected $imageValidate = [
        'image' => 'filesize:10240|fileExt:jpg,png,gif,jpeg,bmp,svg'

    ];
    public function initialize()

    {
//        $fileExt = getConfigByCode('upload_file_type');
//        $filemax = getConfigByCode('upload_file_max')*1024;
//        $this->uploadValidate = ['image'=>
//            'filesize'.$filemax.'|'.$fileExt,
//        ];
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 文件上传
     * @return false|string
     */
    public function Uploads(){
        //获取上传文件表单字段名
        $fileKey = array_keys(request()->file());
        $error = 'upload error';
        for ($i = 0; $i < count($fileKey); $i++) {
            //获取表单上传文件
            $file = request()->file($fileKey[$i]);
            try {
                validate($this->uploadValidate)
                    ->check($this->objToArray($file));
                $savename = \think\facade\Filesystem::disk('public')->putFile('uploads', $file);

                $path[] = '/storage/' . $savename;
            } catch (\think\exception\ValidateException $e) {
                $path = '';
                $error = $e->getMessage();
            }
        }
        if (!empty($path)) {
            $result['code'] = 1;
            //分辨是否截图上传，截图上传只能上传一个，非截图上传可以上传多个
            if (Request::param('responseType') == 'json') {
                $result["url"] = $path[0];
            } else {
                $result["url"] = $path;
            }
            $result['msg'] = lang('upload success');
            return $result;
        } else {
            //上传失败获取错误信息
            $result['url'] = '';
            $result['msg'] = $error;
            $result['code'] = 0;
            return $result;
        }
    }

    public function objToArray($object)
    {
        $array = array();
        if (is_object($object)) {
            foreach ($object as $key => $value) {
                $array[$key] = $value;
            }
        } else {
            $array = $object;
        }
        return $array;
    }

}